import { Collection } from "lokijs";
import { RecordState } from "@/model/frame/IRecordState";

export interface CollectionConstructOptions<T> {
  name: string;
  options?: Partial<CollectionOptions<T>>;
}

export class CollectionConstruct<T extends RecordState> {
  private readonly collection: Collection<T>;

  constructor(db: Loki, options: CollectionConstructOptions<T>) {
    this.collection = db.getCollection<T>(options.name);
    if (!this.collection) {
      this.collection = db.addCollection<T>(options.name, options.options);
      console.log(`创建: ${options.name}`);
    }
  }

  get $(): Collection<T> {
    return this.collection;
  }

  Update(doc: T) {
    doc.updateTime = new Date();
    this.collection.update(doc);
  }
}
export type CollectionOrNull<T extends RecordState> = CollectionConstruct<
  T
> | null;
